#include "detecposition.h"

const int move4[4][2] = {0, 1, 0, -1, 1, 0, -1, 0};
int DetecPosition::backtrack(int x, int y, int idx)
{
    data[x * width + y] = 255 - idx;
    int ret = 1;
    int nx, ny;
    for(int i = 0; i < 4; i++)
    {
        nx = x + move4[i][0];
        ny = y + move4[i][1];
        if(nx < height && ny < width && nx >= 0 && ny >= 0 && data[nx*width + ny] == 255)
        {
            ret += backtrack(nx, ny, idx);
        }
    }
    return ret;
}
CvPoint
DetecPosition::Detect(IplImage *src, IplImage *dst)
{
    data = (uchar*)src->imageData;
    width = src->width;
    height = src->height;
    int idx = 0;
    int mx = 0, mxidx;
    uchar *p = data;
    for(int i = 0; i < height; i++)
        for(int j = 0; j < width; j++)
        {
            if(*p == 255) ++mx;
            p++;
        }
    if(mx > (height * width) / 2) return cvPoint(-1, -1);
    mx = 0;
    for(int i = 10; i < height - 10; i++)
    {
        for(int j = 10; j < width - 10; j++)
        {
            if(data[i*width + j] == 255)
            {cnt[idx] = backtrack(i, j, idx + 1);
                if(mx < cnt[idx]){mx = cnt[idx]; mxidx = idx;}
                if(idx == 254 || mx > width * height /3)
                {
                    return cvPoint(-1, -1);
                }
                idx ++;
                cnt[idx] = backtrack(i, j, idx + 1);
                if(mx < cnt[idx]){mx = cnt[idx]; mxidx = idx;}
                if(idx == 254 || mx > width * height /3)
                {
                    return cvPoint(-1, -1);
                }
                idx ++;
            }
        }
    }
    if(mx < 18000) return cvPoint(-1, -1);
    p = data;
    long long ax, ay;
    ax = ay = 0;
    for(int i = 0; i < height; i++)
    {
        for(int j = 0; j < width; j++)
        {
            if(*p == 254 - mxidx) {
                ax += i;
                ay += j;
                *p = 255;
            }
            else *p = 0;
            p++;
        }
    }
    ax /= mx;
    ay /= mx;
    return cvPoint(ax, ay);
}

